package com.king.juc.atomicdemo.accumulator;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * 累加器案例
 *      通过多个变量累加, 减少CAS重试, 降低耗时
 * @author king
 * @date 2020/12/1 23:05
 */
public class AccumulatorDemo {
    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            demo(
                    () -> new AtomicLong(0),
                    AtomicLong::getAndIncrement
            );
        }

        for (int i = 0; i < 5; i++) {
            demo(
                    LongAdder::new,
                    LongAdder::increment
            );
        }
    }

    /**
     * 累加器演示
     * @param adderSupplier 提供累加器对象
     * @param action 执行累加操作
     * @param <T>
     */
    private static <T> void demo(Supplier<T> adderSupplier, Consumer<T> action){
        T adder = adderSupplier.get();
        List<Thread> ts = new ArrayList<>();
        // 4个线程, 每人累加50万
        for (int i = 0; i < 4; i++) {
            ts.add(new Thread((() -> {
                for (int j = 0; j < 500000; j++) {
                    action.accept(adder);
                }
            })));
        }
        long start = System.nanoTime();
        ts.forEach(t -> t.start());
        ts.forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        long end = System.nanoTime();
        System.out.println(adder + "cost: " + (end - start) / 1000_000);
    }
}
